package com.laikan.reader.bookfriend.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.bean.*;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.utils.Result;
import com.socks.library.KLog;
import com.switfpass.pay.MainApplication;
import com.switfpass.pay.activity.PayPlugin;
import com.switfpass.pay.bean.RequestMsg;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.mobileqq.openpay.api.IOpenApi;
import com.tencent.mobileqq.openpay.api.OpenApiFactory;
import com.tencent.mobileqq.openpay.constants.OpenConstants;
import com.tencent.mobileqq.openpay.data.pay.PayApi;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wx
 * @category 充值页面
 */
@SuppressLint ("HandlerLeak")
public class MoneyPage extends BasicActivity implements OnClickListener {

    private static final int RQF_PAY = 1;
    private static final int RQF_LOGIN = 2;
    final IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);
    PayReq req;
    private String APP_ID = "1105459927"; //qq钱包
    private String callbackScheme = "qwallet1105459927";//回调
    private int paySerial = 1;
    private IOpenApi openApi;
    protected long mRequestInternalTime;
    private ImageView back_tv, zhifubao, caifutong, yinhang, weixin;
    private int type = 0;
    private String money = "";
    private RelativeLayout ten, thirty, fifty, onehundred, twohundred, five_hundred;
    private TextView payway;
    private TextView tv_pay;
    private ImageView icon;
    private ArrayList<Integer> payratio = new ArrayList<Integer>();
    private TextView ten_text, thirty_text, fifty_text, onehundred_text, twohundred_text, five_hundred_text;
    private boolean payAction = false;
    private TextView text7, text2, text3, text4, text5, text6;
    private RelativeLayout back_layout;
    Drawable drawable_back_tv;

    /**
     * 访问支付宝
     */

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            Result payResult = new Result((String)msg.obj);
            String resultInfo = payResult.getResult();

            if (getString(R.string.moneypage_pay_success).equals(resultInfo)) {
                if (SPUtil.getBoolean("signedAction", false)) {
                    LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent("action_signed"));
                }
            }
            switch (msg.what) {

                case RQF_PAY:

                    SPUtil.putBoolean("login_laikan_setting", true);
                case RQF_LOGIN: {
                    // TODO 解析msg.obj

                    // Toast.makeText(getApplicationContext(),
                    // result.parseResult()+"",
                    // Toast.LENGTH_SHORT).show();
                    // //TODO 完善接口
                    // finishOrder();

                }
                SPUtil.putBoolean("login_laikan_setting", true);
                break;
                default:
                    SPUtil.putBoolean("login_laikan_setting", true);
                    break;
            }
        }

    };


    @Override
    protected void assignViews() {
        setContentView(R.layout.money);
        openApi = OpenApiFactory.getInstance(this, APP_ID);
        req = new PayReq();
        msgApi.registerApp(Constants.APP_ID);
        ten_text = (TextView)findViewById(R.id.ten_text);
        thirty_text = (TextView)findViewById(R.id.thirty_text);
        fifty_text = (TextView)findViewById(R.id.fifty_text);
        onehundred_text = (TextView)findViewById(R.id.onehundred_text);
        twohundred_text = (TextView)findViewById(R.id.twohundred_text);
        five_hundred_text = (TextView)findViewById(R.id.five_hundred_text);

        payway = (TextView)findViewById(R.id.tv_title);
        tv_pay = (TextView)findViewById(R.id.tv_pay);
        icon = (ImageView)findViewById(R.id.icon);
        back_tv = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        five_hundred = (RelativeLayout)findViewById(R.id.five_hundred);
        ten = (RelativeLayout)findViewById(R.id.ten);
        thirty = (RelativeLayout)findViewById(R.id.thirty);
        fifty = (RelativeLayout)findViewById(R.id.fifty);
        onehundred = (RelativeLayout)findViewById(R.id.onehundred);
        twohundred = (RelativeLayout)findViewById(R.id.twohundred);
        back_layout.setOnClickListener(this);
        five_hundred.setOnClickListener(this);
        ten.setOnClickListener(this);
        thirty.setOnClickListener(this);
        fifty.setOnClickListener(this);
        onehundred.setOnClickListener(this);
        twohundred.setOnClickListener(this);
        text2 = (TextView)findViewById(R.id.text2);
        text3 = (TextView)findViewById(R.id.text3);
        text4 = (TextView)findViewById(R.id.text4);
        text5 = (TextView)findViewById(R.id.text5);
        text6 = (TextView)findViewById(R.id.text6);
        text7 = (TextView)findViewById(R.id.text7);
        text2.setRotation(40.0f);
        text3.setRotation(40.0f);
        text4.setRotation(40.0f);
        text5.setRotation(40.0f);
        text6.setRotation(40.0f);
        text7.setRotation(40.0f);
    }

    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        back_tv.setImageDrawable(drawable_back_tv);
        SPUtil.putBoolean("login_laikan_setting", true);
//        payratio = getIntent().getIntegerArrayListExtra("payratio");
//        payAction = getIntent().getBooleanExtra("payAction", false);
//        if (payAction) {
//            if (payratio.size() != 0) {
//                String showText = getString(R.string.moneypage_read_note);
//                ten_text.setText("+" + payratio.get(1) + showText);
//                thirty_text.setText("+" + payratio.get(2) + showText);
//                fifty_text.setText("+" + payratio.get(3) + showText);
//                onehundred_text.setText("+" + payratio.get(4) + showText);
//                twohundred_text.setText("+" + payratio.get(5) + showText);
//                if (payratio.size() >= 7) {
//                    five_hundred_text.setText("+" + payratio.get(6) + showText);
//                }
//                int payratio1, payratio2, payratio3, payratio4, payratio5, payratio6, payratio7;
//                payratio1 = payratio.get(0) / 100;
//                payratio2 = payratio.get(1) / 100;
//                payratio3 = payratio.get(2) / 100;
//                payratio4 = payratio.get(3) / 100;
//                payratio5 = payratio.get(4) / 100;
//                payratio6 = payratio.get(5) / 100;
//                payratio7 = 0;
//                if (payratio.size() >= 7) {
//                    payratio7 = payratio.get(6) / 100;
//                }
//                String showPrefix = getString(R.string.moneypage_send);
//                String showSuffix = getString(R.string.moneypage_yuan);
//                text2.setText(showPrefix + payratio2 + showSuffix);
//                text3.setText(showPrefix + payratio3 + showSuffix);
//                text4.setText(showPrefix + payratio4 + showSuffix);
//                text5.setText(showPrefix + payratio5 + showSuffix);
//                text6.setText(showPrefix + payratio6 + showSuffix);
//                if (payratio.size() >= 7) {
//                    text7.setText(showPrefix + payratio7 + showSuffix);
//                }
//            }
//        }else {
//            five_hundred.setBackgroundColor(Color.WHITE);
//            ten.setBackgroundColor(Color.WHITE);
//            thirty.setBackgroundColor(Color.WHITE);
//            fifty.setBackgroundColor(Color.WHITE);
//            onehundred.setBackgroundColor(Color.WHITE);
//            twohundred.setBackgroundColor(Color.WHITE);
//            text2.setText("");
//            text3.setText("");
//            text4.setText("");
//            text5.setText("");
//            text6.setText("");
//            text7.setText("");
//        }

        type = getIntent().getIntExtra("type", 0);
        switch (type) {
            case 1:

                payway.setText(R.string.moneypage_alipay_recharge);
                tv_pay.setText(R.string.moneypage_alipay);
                icon.setBackgroundResource(R.drawable.zhifubao_pay);
                break;
            case 2:
                payway.setText(R.string.moneypage_tenpay_recharge);
                tv_pay.setText(R.string.moneypage_tenpay);
                icon.setBackgroundResource(R.drawable.caifutong_pay);
                break;
            case 3:
                payway.setText(R.string.moneypage_online_bank_recharge);
                tv_pay.setText(R.string.moneypage_online_bank);
                icon.setBackgroundResource(R.drawable.wangyin_pay);
                break;
            case 4:
                payway.setText(R.string.moneypage_wechat_recharge);
                tv_pay.setText(R.string.moneypage_wechat);
                icon.setBackgroundResource(R.drawable.weixin_pay);
                break;
            case 6:
                payway.setText(R.string.moneypage_qqwallet_recharge);
                tv_pay.setText(R.string.moneypage_qqwallet);
                icon.setBackgroundResource(R.drawable.qqwallet_icon);
                break;
        }
    }

    @Override
    protected void setListener() {
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_layout:
                finish();
                break;
            case R.id.ten:
                money = "10";
                putVaule(type);
                break;
            case R.id.thirty:
                money = "30";
                putVaule(type);
                break;
            case R.id.fifty:
                money = "50";
                putVaule(type);
                break;
            case R.id.onehundred:
                money = "100";
                putVaule(type);
                break;
            case R.id.twohundred:
                money = "200";
                putVaule(type);
                break;
            case R.id.five_hundred:
                money = "500";
                putVaule(type);
                break;
        }

    }

    private boolean internalTime(long currentTime) {
        if (mRequestInternalTime > currentTime) {
            return true;
        }
        return false;
    }

    public void putVaule(int type) {
        if (internalTime(System.currentTimeMillis())) {
            return;
        }
        mRequestInternalTime = System.currentTimeMillis() + 2000;

        switch (type) {
            case 1: // 支付宝
                aliPay();
                break;

            case 2: // 财付通
                getDate(money);
                break;

            case 3: // 网银
                getDate(money);
                break;

            case 4: // 微信
                mRequestInternalTime = System.currentTimeMillis() + 3000;
                getWXOrder();
                break;
            case 6:
                if(onBtnIsMqqInstalled()){
                    if(onBtnIsMqqSupportPay()){
                        qqWallet();
                    }else{
                        ToastMgr.showShortToast(R.string.qqwallet_errer_msg1);
                    }
                }else{
                    ToastMgr.showShortToast(R.string.qqwallet_errer_msg2);
                }
                break;
        }
    }

    /**
     * 判断是否有QQ
     * @return
     */
    private boolean onBtnIsMqqInstalled() {

        String ss;
        try {
            ss = Base64.encodeToString("0612".getBytes("UTF-8"), Base64.NO_WRAP);
            Log.e("guojiel", "Base64: " + ss);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        boolean isInstalled = openApi.isMobileQQInstalled();
        return isInstalled;
    }
    private boolean onBtnIsMqqSupportPay() {
        boolean isSupport = openApi.isMobileQQSupportApi(OpenConstants.API_NAME_PAY);
        return isSupport;
    }

    // TODO: 9/13/16 checkhere
    public void setView(String url) {
        Intent intent = new Intent(this, TenpayAndBank.class);
        intent.putExtra("mHtmlUrl", url);
        intent.putExtra("type", type);
        if (type == 2) {
            intent.putExtra("title", getString(R.string.moneypage_tenpay_pay));
        }else if (type == 3) {
            intent.putExtra("title", getString(R.string.moneypage_online_bank_pay));
        }

        startActivity(intent);
        finish();
    }



    /**
     * QQ钱包支付
     */
    private void qqWallet() {
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("amount", money);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {  }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    BaseDataBean<QQWalletBean> result = null;
                    Type type = new TypeToken<BaseDataBean<QQWalletBean>>() {}.getType();
                    Gson gson = new Gson();
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (Constants.RESULT_OK.equals(result.getResult())) {
                         QQWalletBean qQWalletBean = result.getData();
                        if(qQWalletBean!=null){
                            exeQQWallet(qQWalletBean);
                        }
                    }else {
                        ToastMgr.showShortToast(result.getError_msg());
                    }

                }catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
            }

            @Override
            public void onFinish() {
            }
        };

        Requester requester = new Requester();
        requester.setUrl("http://laikan.motie.com/app_qqpay/ordering");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest("http://laikan.motie.com/app_qqpay/ordering", map, null, null, requestListener);

    }
    private void exeQQWallet(QQWalletBean qQWalletBean){

        PayApi api = new PayApi();
        api.appId = APP_ID;
        api.serialNumber = qQWalletBean.getSerialNumber(); //支付序号,用于标识此次支付
        api.callbackScheme = callbackScheme;// QQ钱包支付结果回调给urlscheme为callbackScheme的activity.,
        api.tokenId = qQWalletBean.getTokenId(); // QQ钱包支付生成的token_id
        api.pubAcc = ""; // 手Q公众帐号id.参与支付签名,签名关键字key为pubAcc
        api.pubAccHint = "";// 支付完成页面,展示给用户的提示语:提醒关注公众帐号
        api.nonce = qQWalletBean.getNonce();// 随机字段串,每次支付时都要不一样.参与支付签名,签名关键字key为nonce
        api.timeStamp = Long.parseLong(qQWalletBean.getTimeStamp());// 时间戳,为1970年1月1日00:00到请求发起时间的秒数
        api.bargainorId = qQWalletBean.getBargainorId(); // 商户号.参与支付签名,签名关键字 key 为 bargainorId
        api.sig = qQWalletBean.getSig();
        api.sigType = "HMAC-SHA1";
        if (api.checkParams()) {
            openApi.execApi(api);
        }
    }
    /**
     * 支付宝支付
     */
    private void aliPay() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("amount", money);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    BaseDataBean<AliPayBean> result = null;
                    Type type = new TypeToken<BaseDataBean<AliPayBean>>() {}.getType();
                    Gson gson = new Gson();
                    System.out.println(httpResponse.responseContent);
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (Constants.RESULT_OK.equals(result.getResult())) {
                        final AliPayBean aliPayBean = result.getData();
                        if(aliPayBean!=null){
                            new Thread() {
                                public void run() {
                                    PayTask alipay = new PayTask(MoneyPage.this);
                                    String result = alipay.pay(aliPayBean.getInfo());
                                    Message msg = new Message();
                                    msg.what = RQF_PAY;
                                    msg.obj = result;
                                    mHandler.sendMessage(msg);
                                }
                            }.start();
                        }
                    }else {
                        ToastMgr.showShortToast(result.getError_msg());
                    }

                }catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。27");
            }

            @Override
            public void onFinish() {
            }
        };

        Requester requester = new Requester();
        requester.setUrl("http://laikan.motie.com/adn_alipay/ordering");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest("http://laikan.motie.com/adn_alipay/ordering", map, null, null, requestListener);

    }

    /**
     * 财付通和银行卡支付方式
     */
    private void getDate(String money) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("amount", money);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                BaseDataBean<BaseListDataBean<Consume>> result;
                Gson gson = new Gson();
                Type type = new TypeToken<BaseDataBean<BaseListDataBean>>() {
                }.getType();
                try {
                    result = gson.fromJson(httpResponse.responseContent, type);
                    setView(result.getData().getUrl());
                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    ToastMgr.showShortToast(R.string.laikan_data_load_failed);
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。28");
            }

            @Override
            public void onFinish() {
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "accounts/tenPay");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.getRootURL2() + "accounts/tenPay", map, null, null, requestListener);

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }

    /**
     * WIFI 获取IP
     *
     * @return
     */
    private String getWifiIPoRLocalIp() {
        // 获取wifi服务
        WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        // 判断wifi是否开启
        if (wifiManager.isWifiEnabled()) {
            // 开启wifi
            // wifiManager.setWifiEnabled(true);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            String ip = intToIp(ipAddress);
            return ip;
        }else {
            return getLocalIpAddress();
        }
    }

    private String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
    }

    /**
     * GPRS 获取IP
     *
     * @return
     */
    public String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        }catch (SocketException ex) {
            KLog.e("886 " + ex.toString());
        }
        return null;
    }

    ///////////////////////////////////////微信支付调用后台新下单接口//////////////////////////////////////////
    private void getWXOrder() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("sd", SPUtil.getString("token", ""));
        map.put("amount", money);
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() { KLog.e("---------volley onPreExecute!!!"); }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                try {
                    BaseDataBean<WFTBean> result = null;
                    Type type = new TypeToken<BaseDataBean<WFTBean>>() {}.getType();
                    Gson gson = new Gson();
                    System.out.println(httpResponse.responseContent);
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (Constants.RESULT_OK.equals(result.getResult())) {

                        RequestMsg msg = new RequestMsg();
                        msg.setTokenId(result.getData().getTokenId());
                        msg.setTradeType(MainApplication.PAY_WX_WAP);
                        PayPlugin.unifiedH5Pay(MoneyPage.this, msg);

                    }else {
                        KLog.e(" 111111 " + result.getError_msg());
                        ToastMgr.showShortToast(result.getError_msg());
                    }

                }catch (JsonSyntaxException e) {

                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                ToastMgr.showShortToast(R.string.laikan_network_anomaly);
                KLog.e("网络不给力，请重试。29");
            }

            @Override
            public void onFinish() {
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.laikan_weixinpay);
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);

//        HttpApiRequestEngine.getInstance().httpPostRequest(APIProtocol.laikan_weixinpay, map, null, null, requestListener);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data == null) {
            return;
        }

        String respCode = data.getExtras().getString("resultCode");
        if (!TextUtils.isEmpty(respCode) && respCode.equalsIgnoreCase("success")) {

            if (SPUtil.getBoolean("signedAction", false)) {
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent("action_signed"));
            }
            //标示支付成功
            Toast.makeText(MoneyPage.this, R.string.moneypage_pay_success, Toast.LENGTH_LONG).show();
        }else { //其他状态NOPAY状态：取消支付，未支付等状态
            Toast.makeText(MoneyPage.this, R.string.moneypage_no_pay, Toast.LENGTH_LONG).show();
        }

        super.onActivityResult(requestCode, resultCode, data);

    }

}
